package com;

import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XMLReader {
	public XMLReader(){
		super();
	}
	
	public void setUserList(){
		LoadAppString.cleanUsers();
		try{
			SAXReader reader = new SAXReader();
			Document doc = reader.read(FileURL.getXMLURL());
			Element root = doc.getRootElement();
			Iterator it = root.elements("author").iterator();
			
			while(it.hasNext()){
				Element el = (Element)it.next();
				String userId = el.attributeValue("id");
				String userName = el.element("userName").getText();
				String university = el.element("university").getText();
				
				LoadAppString.setUserList(userId, userName + "-" + university);
			}
			
		}catch(DocumentException de){
			de.printStackTrace();
		}
	}
	
	public void setUserApp(String userId){
		LoadAppString.cleanApps();
		try{
			SAXReader reader = new SAXReader();
			Document doc = reader.read(FileURL.getXMLURL());
			Element root = doc.getRootElement();
			Iterator it = root.elements("author").iterator();
			
			while(it.hasNext()){
				Element el = (Element)it.next();
				if(el.attributeValue("id").equals(userId)){
					Element appNode = el.element("webapps");
					Iterator apps = appNode.elements("webapp").iterator();
					
					while(apps.hasNext()){
						Element node = (Element)apps.next();
						String name = node.element("name").getText();
						String url = node.element("url").getText();
						LoadAppString.setExtend(name, url);
					}
					break;
				}
			}
			
		}catch(DocumentException de){
			de.printStackTrace();
		}
	}
}
